/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.wiztools.xpathevaluator;

import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 *
 * @author subwiz
 */
public class Util {
    
    public static final int WIDTH = 5;
    
    private static final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    private static final XPathFactory factory = XPathFactory.newInstance();
    private static final XPath xpath = factory.newXPath();
    static{
        domFactory.setNamespaceAware(true);
    }
    
    public static Object evaluateXPath(String xml, String xpathStr, QName returnType) throws Exception{
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
        Object result = xpath.evaluate(xpathStr, doc, returnType);
        if(XPathConstants.NODESET.equals(returnType)){
            NodeList nodes = (NodeList) result;
            List<String> ll = new ArrayList<String>();
            for (int i = 0; i < nodes.getLength(); i++) {
                ll.add(nodes.item(i).getNodeValue()); 
            }
            return ll;
        }
        else if(XPathConstants.STRING.equals(returnType)){
            return (String)result;
        }
        else if(XPathConstants.NUMBER.equals(returnType)){
            return (Double)result;
        }
        else if(XPathConstants.BOOLEAN.equals(returnType)){
            return (Boolean)result;
        }
        return null;
    }

    public static QName getQNameFromStr(String str){
        if("String".equals(str)){
            return XPathConstants.STRING;
        }
        else if("Number".equals(str)){
            return XPathConstants.NUMBER;
        }
        else if("Boolean".equals(str)){
            return XPathConstants.BOOLEAN;
        }
        else{
            throw new IllegalArgumentException();
        }
    }
    
    public static String getStackTrace(final Throwable aThrowable) {
        String errorMsg = aThrowable.getMessage();
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        aThrowable.printStackTrace(printWriter);
        return errorMsg + "\n" + result.toString();
    }
}
